package com.study.springsecurity.service.security;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.springsecurity.constant.CommonConstant;
import com.study.springsecurity.mapper.RoleInfoMapper;
import com.study.springsecurity.mapper.UserInfoMapper;
import com.study.springsecurity.pojo.MyUserDetails;
import com.study.springsecurity.pojo.entity.RoleInfoEntity;
import com.study.springsecurity.pojo.entity.UserInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DBUserDetailsService implements UserDetailsService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    
    @Autowired
    private RoleInfoMapper roleInfoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserInfoEntity> wrapper = new QueryWrapper();
        wrapper.eq("username", username);
        UserInfoEntity userInfoEntity = userInfoMapper.selectOne(wrapper);
        if (userInfoEntity == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        // 获取用户角色、菜单列表
        List<RoleInfoEntity> roleInfoEntityList = roleInfoMapper.selectRoleByUserId(userInfoEntity.getId());
        log.info("DBUserDetailsService username={},roles={}", username, JSON.toJSONString(roleInfoEntityList));

        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>(); // 声明一个集合List<GrantedAuthority>
//         List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.commaSeparatedStringToAuthorityList("role1,role2");
//         List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.createAuthorityList(menus.toArray(new String[0]));

        // 处理角色
        for (RoleInfoEntity roleInfoEntity : roleInfoEntityList) {
            // 角色之所以要使用ROLE_开头，是为了和ExpressionUrlAuthorizationConfigurer.AuthorizedUrl.hasRole(String role)方法一致
            grantedAuthorityList.add(new SimpleGrantedAuthority(CommonConstant.Role.ROLE_PREFIX + roleInfoEntity.getRoleCode()));
        }

        return new MyUserDetails(userInfoEntity.getId(), userInfoEntity.getUsername(), userInfoEntity.getPassword(), grantedAuthorityList);
    }
}
